<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    /**
     * 分类列表
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $type = $request->input('all');
        if ($type == 'all'){
            return cache_category_all();
        }else{
            return cache_category();
        }

    }

    /**
     * 添加分类 最大不超过3级
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $insertData = $this->checkInput($request);

        if(!is_array($insertData)) return $insertData;

         Category::create($insertData);


        return $this->response->created();

    }

    /**
     * 分类详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        return $category;
    }

    /**
     * 修改分类
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        $updateData = $this->checkInput($request);

        if(!is_array($updateData)) return $updateData;

        //批量赋值  update方法
        // Category::where('id',$category->id)->update($updateData);

        $category->update($updateData);


        return $this->response->noContent();
    }

    public function checkInput($request)
    {
        // 验证参数
        $request->validate([
            'name' => 'required|max:16'
        ],[
            'name.required' => '分类名称不能为空',
            'name.max' => '分类名称最多不能超过16位字符'
        ]);
        //获取pid
        $pid = $request->input('pid',0);

        // 获取分组
        $group = $request->input('group', 'goods');

        // 计算level且不能超过3级
        $level = $pid == 0 ? 1 : (Category::find($pid)->level + 1);

        if($level > 3){
            return $this->response->errorBadRequest('不能超过三级分类');
        }

        return [
            'name' => $request->input('name'),
            'pid' => $pid,
            'level' => $level,
            'group' => $group
        ];
    }

    /**
     * //禁用分类/启用分类
     * @param Category $category
     * @return \Dingo\Api\Http\Response
     */
    public function status(Category $category)
    {
        $category->status = $category->status == 1 ? 0 : 1;

        $category->save();

        return $this->response->noContent();
    }

}
